import { defineStore } from 'pinia'
import pinia from '@/store/index'  // createPinia()

export const useUserStore = defineStore({
  id: 'user', // id必填，且唯一
  state: () => {
    return {
      userId: '', // 用户id
      username: '', // 用户名
      token: '', // token
      avatarUrl: '', // 头像url
      userInfo: '', // 用户信息
    }
  },
  actions: {
    setUserId(userId: string) {
      this.userId = userId;
    },
    clearUserId() {
      this.userId = '';
    },
    setUserName(username: string) {
      this.username = username;
    },
    clearUserName() {
      this.username = '';
    },
    setToken(token: string) {
      this.token = token;
    },
    clearToken() {
      this.token = '';
    },
    setAvatarUrl(avatarUrl: string) {
      this.avatarUrl = avatarUrl;
    },
    clearAvatarUrl() {
      this.avatarUrl = '';
    },
    setUserInfo(userInfo: string) {
      this.userInfo = userInfo;
    },
    clearUserInfo() {
      this.userInfo = '';
    }
  }
})

// 数据持久化
// 1. 保存数据
const instance = useUserStore(pinia);
instance.$subscribe((_, state) => {
  localStorage.setItem('userid', state.userId);
  localStorage.setItem('username', state.username);
  localStorage.setItem('token', state.token);
  localStorage.setItem('avatarUrl', state.avatarUrl);
  localStorage.setItem('userinfo', state.userInfo);
});
// 2. 获取保存的数据，先判断有无，无则用先前的
const oldUserId = localStorage.getItem('userid');
if (oldUserId) {
  instance.$state.userId = oldUserId;
}
const oldUsername = localStorage.getItem('username');
if (oldUsername) {
  instance.$state.username = oldUsername;
}
const oldToken = localStorage.getItem('token');
if (oldToken) {
  instance.$state.token = oldToken;
}
const oldAvatarUrl = localStorage.getItem('avatarUrl');
if (oldAvatarUrl) {
  instance.$state.avatarUrl = oldAvatarUrl;
}
const oldUserInfo = localStorage.getItem('userinfo');
if (oldUserInfo) {
  instance.$state.userInfo = oldUserInfo;
}